/**
 * @description formula plugin
 * @author snake
 */

import { DomEditor, SlateTransforms, IDomEditor } from '@wangeditor/editor'

/**
 * witchPlaceholder 插件
 * @param {*} editor 
 * @returns 
 */
function witchPlaceholder(editor) {
  const { isInline, isVoid, normalizeNode } = editor
  const newEditor = editor

  // 重写 isInline
  newEditor.isInline = (elem) => {
    const { type } = elem

    if (type === 'placeholder') return true // 针对 type: placeholder ，设置为 inline

    return isInline(elem)
  }
 
  // 重写 isVoid
  newEditor.isVoid = (elem) => {
    const { type } = elem

    if (type === 'placeholder') return true // 针对 type: placeholder ，设置为 inline

    return isVoid(elem)
  }

  // 重写 normalizeNode
  newEditor.normalizeNode = ([node, path]) => {
    const type = DomEditor.getNodeType(node)

    if (type === 'placeholder') {
      // placeholder 是 editor 最后一个节点，需要后面插入 p
      const isLast = DomEditor.isLastNode(newEditor, node)
      if (isLast) {
        Transforms.insertNodes(newEditor, DomEditor.genEmptyParagraph(), {
          at: [path[0] + 1]
        })
      }
    }

    // 执行默认的 normalizeNode ，重要！！！
    return normalizeNode([node, path])
  }

  return newEditor
}

export default witchPlaceholder
